package com.xatz.scanner

import android.content.Context
import android.media.RingtoneManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.DataTable
import com.xatz.scanner.databinding.ActivitySalesBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader
import java.util.concurrent.Executors


/**
 * author: tdq
 * date: 2021/7/20
 * description: 销售出库
 */
class SalesActivity : AppCompatActivity(),
    ScannerManger.OnScannerResultListener {

    private lateinit var mBinding: ActivitySalesBinding

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    //用于存放上一点击返回键的时刻
    private var mExitTime: Long = 0

    private var dialog: CustomDialog? = null

    private val titles = arrayOf("执行页", "查询页", "结果页", "汇总")

    private val mExecutionPageFragment = ExecutionPageFragment()
    private val mSelectPageFragment = SelectPageFragment()
    private val mResultPageFragment = ResultPageFragment()
    private val mTotalPageFragment = TotalPageFragment()

    private var mTableData: DataTable? = null

    private var count = 0

    private var countTotal = 0.0

    private val mFragments = arrayListOf(
        mExecutionPageFragment,
        mSelectPageFragment,
        mResultPageFragment,
        mTotalPageFragment
    )

    private val mHandler = Handler(Looper.getMainLooper()) {
        if (it.what == 1) {
            val resultMsg = it.obj
            toast(resultMsg.toString())
        }
        false
    }

    // 是否获取了发运单
    private var isScannerOne = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivitySalesBinding.inflate(layoutInflater)
        mBinding.toolbarLayout.setLeftDrawable(0, false)
        setContentView(mBinding.root)
        ScannerManger.init(this)
        ScannerManger.setOnScannerResultListener(this)
        repeat(titles.count()) {
            mBinding.tlLayout.addTab(mBinding.tlLayout.newTab())
        }
        mBinding.tlLayout.setupWithViewPager(mBinding.vpSales, false)

        val pagerAdapter = object : FragmentStatePagerAdapter(supportFragmentManager, 0) {
            override fun getCount(): Int = mFragments.size
            override fun getItem(position: Int): Fragment = mFragments[position]
        }
        mBinding.vpSales.adapter = pagerAdapter
        mBinding.vpSales.offscreenPageLimit = 3

        for (i in titles.indices) {
            mBinding.tlLayout.getTabAt(i)?.text = titles[i]
        }
        dialog = CustomDialog(this)
    }

    override fun onScannerResult(data: String?, labelType: String) {
        data?.run {
            if (this.startsWith("SO")) {
                // 一维码
//                if (!isScannerOne) {
                getDataInfoOnNet(this)
//                }
//                else {
//                    runOnUiThread {
//                        Toast.makeText(this@SalesActivity, "已扫描提单条码", Toast.LENGTH_SHORT).show()
//                    }
//                }
            } else {
                // 二维码
                if (isScannerOne) {
//                    if (mResultPageFragment.mDatas.isNotEmpty()) {
//                        val outDatasBean = mResultPageFragment.mDatas.find { this == it.piece }
//                        if (outDatasBean != null) {
//                            val msg = Message.obtain()
//                            msg.what = 1
//                            msg.obj = this
//                            mHandler.sendMessage(msg)
//                        } else {
//                            scannerResultHandle(this)
//                        }
//                    } else {
                    if (mBinding.tlLayout.getTabAt(2)?.isSelected != true) {
                        mExecutionPageFragment.setBarCodeShow(data)
                        scannerResultHandle(this)
                    } else {
                        mResultPageFragment.setBarCodeShow(data)
                    }
//                    }
                } else {
                    runOnUiThread {
                        toast("请先扫描提单条码")
                    }
                }
            }
        }

    }

    fun repeatScannerHandle(piece: String) {
        AlertDialog.Builder(this).setTitle("提示")
            .setMessage("确定要删除条码${piece}吗？")
            .setPositiveButton("确定") { dialog, _ ->
                dialog.dismiss()
                Executors.newSingleThreadExecutor().submit { delScannerResultHandle(piece) }
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }.show()

    }

    /***
     * 获取条形码数据
     */
    fun getDataInfoOnNet(code: String) {
        mService.getFYDInfo(code, "销售出库").enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { tabStr ->
                        val tableData = parseXMLWithPull(tabStr)
                        mTableData = tableData
                        if (tableData?.C_DELIVERY?.isNotBlank() == true) {
                            clearData()
                            notificationOneFragments(tableData)
                            isScannerOne = true
                        } else {
                            toast("获取失败")
                        }
                    }
                } else {
                    toast("获取失败")
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Timber.e(t)
                toast("获取失败")
            }

        })
    }

    private fun notificationOneFragments(tableData: DataTable) {
        mExecutionPageFragment.onScannerResult(tableData)
        mTotalPageFragment.onScannerResult(tableData)
        mSelectPageFragment.onScannerResult(tableData)
        mResultPageFragment.setOrderNumber(tableData.C_DELIVERY, tableData.C_PLATE_NUMBER)
    }

    private fun notificationTwoFragments() {
        mExecutionPageFragment.countResult(count, countTotal)
        mTableData?.C_DELIVERY?.let { mResultPageFragment.onScannerResult(it) }
        mTableData?.C_DELIVERY?.let { mTotalPageFragment.onScannerResult(it) }
    }

    private fun notificationDelFragments() {
        mTableData?.C_DELIVERY?.let { mResultPageFragment.onScannerDelResult(it) }
        mTableData?.C_DELIVERY?.let { mTotalPageFragment.onScannerResult(it) }
    }

    fun setCountAndWeight(count: Int, weight: Double){
        this.count = count
        this.countTotal = weight
        mExecutionPageFragment.countResult(count,weight)
    }


    override fun onDestroy() {
        super.onDestroy()
        ScannerManger.onClosed()
    }

    override fun onResume() {
        super.onResume()
        // The application is in foreground
        if (ScannerManger.emdkManager != null) {
            // Acquire the barcode manager resources
            ScannerManger.initBarcodeManager(this)
        }
    }

    override fun onPause() {
        super.onPause()
        // The application is in background
        // Release the barcode manager resources
        ScannerManger.deInitScanner()
        ScannerManger.deInitBarcodeManager()
    }

    private fun parseXMLWithPull(xmlData: String): DataTable? {
        var C_DELIVERY = ""
        var C_DELIVERY_ID = ""
        var C_PLAN_DATE = ""
        var C_CUST_NO = ""
        var N_PLAN_WGT = ""
        var C_CUST_NAME = ""
        var C_PLATE_NUMBER = ""
        var C_PZ = ""
        var C_MAT_CODE = ""
        var C_MAT_DESC = ""
        var C_FSTATUS = ""
        var DINGDANLEIXING = ""
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "C_DELIVERY" -> C_DELIVERY = xmlPullParser.nextText()
                            "C_DELIVERY_ID" -> C_DELIVERY_ID = xmlPullParser.nextText()
                            "C_PLAN_DATE" -> C_PLAN_DATE = xmlPullParser.nextText()
                            "C_CUST_NO" -> C_CUST_NO = xmlPullParser.nextText()
                            "N_PLAN_WGT" -> N_PLAN_WGT = xmlPullParser.nextText()
                            "C_CUST_NAME" -> C_CUST_NAME = xmlPullParser.nextText()
                            "C_PLATE_NUMBER" -> C_PLATE_NUMBER = xmlPullParser.nextText()
                            "C_PZ" -> C_PZ = xmlPullParser.nextText()
                            "C_MAT_CODE" -> C_MAT_CODE = xmlPullParser.nextText()
                            "C_MAT_DESC" -> C_MAT_DESC = xmlPullParser.nextText()
                            "C_FSTATUS" -> C_FSTATUS = xmlPullParser.nextText()
                            "DINGDANLEIXING" -> DINGDANLEIXING = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
        return DataTable(
            C_DELIVERY,
            C_DELIVERY_ID,
            C_PLAN_DATE,
            C_CUST_NO,
            N_PLAN_WGT,
            C_CUST_NAME,
            C_PLATE_NUMBER,
            C_PZ,
            C_MAT_CODE,
            C_MAT_DESC,
            C_FSTATUS,
            DINGDANLEIXING,
            ""
        )
    }

    fun scannerResultHandle(barcode: String) {
        val userAccount =
            getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                .getString(Constant.userAccount, "").toString()
        val method = "ScanProductCommon"
        //可能是namspace+method拼接
        val soapAction = "http://tempuri.org/ScanProductCommon"
        val request = SoapObject(ScannerService.namespace, method)
        //参数一定注意要有序，尽管是addProperty（），不要当作HttpUrl可以使用LinkedHashMap封装
        request.addProperty("userId", userAccount)
        request.addProperty("billcode", mTableData?.C_DELIVERY)
        request.addProperty("barcode", barcode)
        val envelope = SoapSerializationEnvelope(ScannerService.envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(ScannerService.transUrl)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("ScanProductCommonResult") as SoapObject
            val resultCode = responseSoapObject.getProperty("resultCode").toString()
            val resultMsg = responseSoapObject.getProperty("resultMsg").toString()
            Timber.e(resultCode)
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            if (resultCode == "0") {
                val double = responseSoapObject.getProperty("dec_data").toString().toDouble()
                runOnUiThread {
                    countTotal += double.toString().toDouble()
                    ++count
                    notificationTwoFragments()
                }
            } else {
                runOnUiThread {
                    if (dialog?.isShowing == false) {
                        dialog?.contextText = resultMsg
                        dialog?.showDialog()
                    }
                    val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                    RingtoneManager.getRingtone(this,uri).play()
                }
            }
        } catch (e: Exception) {
            Timber.e(e)
        }
    }

    private fun delScannerResultHandle(barcode: String) {
        val userName =
            getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                .getString(Constant.userName, "").toString()
        val userAccount =
            getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                .getString(Constant.userAccount, "").toString()
        val method = "DelScanProductCommon"
        //可能是namspace+method拼接
        val soapAction = "http://tempuri.org/DelScanProductCommon"
        val request = SoapObject(ScannerService.namespace, method)
        //参数一定注意要有序，尽管是addProperty（），不要当作HttpUrl可以使用LinkedHashMap封装
        request.addProperty("userId", userAccount)
        request.addProperty("billcode", mTableData?.C_DELIVERY)
        request.addProperty("barcode", barcode)
        val envelope = SoapSerializationEnvelope(ScannerService.envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(ScannerService.transUrl)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("DelScanProductCommonResult") as SoapObject
            val resultCode = responseSoapObject.getProperty("resultCode").toString()
            val resultMsg = responseSoapObject.getProperty("resultMsg").toString()
            runOnUiThread {
                if (resultCode == "0") {
                    val double = responseSoapObject.getProperty("dec_data").toString().toDouble()
                    if (countTotal > 0) {
                        countTotal -= double
                    }

                    if (count > 0) {
                        --count
                    }

                    notificationDelFragments()
                    if (dialog?.isShowing == false) {
                        dialog?.contextText = "删除成功"
                        dialog?.showDialog()
                    }
                } else {
                    runOnUiThread {
                        if (dialog?.isShowing == false) {
                            dialog?.contextText = resultMsg
                            dialog?.showDialog()
                        }
                        val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                        RingtoneManager.getRingtone(this,uri).play()
                    }
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if (System.currentTimeMillis() - mExitTime > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show()
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis()
            } else {
                mExitTime = 0L
                //小于2000ms则认为是用户确实希望退出程序
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun clearData() {
        mExecutionPageFragment.clearData()
        mSelectPageFragment.clearData()
        mResultPageFragment.clearData()
        mTotalPageFragment.clearData()
        count = 0
        isScannerOne = false
    }

}